package com.yjy.fuyao.ucenter.api;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.gson.Gson;
import com.yjy.fuyao.ucenter.entity.User;
import com.yjy.fuyao.ucenter.entity.query.UserQuery;
import com.yjy.fuyao.ucenter.entity.vo.LoginVo;
import com.yjy.fuyao.ucenter.entity.vo.RegisterVo;
import com.yjy.fuyao.ucenter.service.UserService;
import com.yjy.fuyao.ucenter.util.HttpClientUtils;
import com.yjy.fuyao.ucenter.util.TcCheckCodeProperties;
import com.yjy.fuyao.utils.exception.BusinessException;
import com.yjy.fuyao.utils.result.R;
import com.yjy.fuyao.utils.result.ResponseEnum;
import com.yjy.fuyao.utils.util.JwtUtils;
import com.yjy.fuyao.utils.util.MD5;
import com.yjy.fuyao.utils.vo.UserVo;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 会员表 前端控制器
 * </p>
 *
 * @author yjy
 * @since 2021-08-21
 */
@RestController
@RequestMapping("/api/ucenter/user")
public class ApiUserController {

    @Autowired
    private RedisTemplate redisTemplate;

    @Resource
    private UserService userService;

    @ApiOperation(value = "会员登录")
    @PostMapping("/login")
    public R login(@RequestBody LoginVo loginVo) {
        String token = userService.login(loginVo);
        return R.ok().data("token", token);
    }

    @ApiOperation(value = "会员注册")
    @PostMapping("/register")
    public R register(@RequestBody RegisterVo registerVo){
        userService.register(registerVo);
        return R.ok();
    }

    @ApiOperation(value = "根据token获取登录信息")
    @GetMapping("/auth/getLoginInfo")
    public R getLoginInfo(HttpServletRequest request){
        try {
            String userId = JwtUtils.getUserIdByJwtToken(request);
            if(userId == ""){
                return R.setResult(ResponseEnum.LOGIN_AUTH_ERROR);
            }
            User user = userService.getLoginInfo(userId);
            System.out.println("R:"+R.ok());
            return R.ok().data("item", user);
        }catch (Exception e){
            e.printStackTrace();
            throw new BusinessException("error",20001);
        }
    }

    @ApiOperation(value = "根据id获取用户信息")
    @GetMapping("/getInfo/{userId}")
    public UserVo getUserInfo(@PathVariable String userId){

        try {
            User user = userService.getLoginInfo(userId);
            UserVo userVo = new UserVo();
            BeanUtils.copyProperties(user,userVo);
            return userVo;
        }catch (Exception e){
            e.printStackTrace();
            throw new BusinessException("error",20001);
        }

    }

    @GetMapping(value = "/list/{page}/{limit}")
    public R pageUserList(@ApiParam(name = "page", value = "当前页码", required = true)
                              @PathVariable Long page,

                          @ApiParam(name = "limit", value = "每页记录数", required = true)
                              @PathVariable Long limit,

                          @ApiParam(name = "userQuery", value = "查询对象", required = false)
                              UserQuery userQuery) {
        Page<User> pageParam = new Page<User>(page, limit);
        IPage<User> pageModel = userService.listPage(pageParam,userQuery);
        return R.ok().data("pageModel",pageModel);
    }

    @PostMapping(value = "/change/isDisabled/{id}/{isDisabled}")
    public R changeIsDisabled(@PathVariable("id") String id,@PathVariable("isDisabled") Integer isDisabled) {
        boolean result = userService.changeIsDisabled(id, isDisabled);
        if (!result) {
            return R.error().message("操作失败");
        }
        return R.ok();
    }

    @GetMapping(value = "/countRegister/{day}")
    public R registerCount(
            @PathVariable String day){
        Integer count = userService.countRegisterByDay(day);
        return R.ok().data("countRegister", count);
    }

    @PostMapping(value = "/changepw/{id}/{oldPw}/{newPw}")
    public R changePassword(@PathVariable("id") String id,@PathVariable("oldPw") String oldPw,@PathVariable("newPw") String newPw){
        User user = userService.getById(id);
        if(!MD5.encrypt(oldPw).equals(user.getPassword())) {
            return R.error().message("密码不正确");
        }else{
            LambdaUpdateWrapper<User> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.set(User::getPassword,MD5.encrypt(newPw)).eq(User::getId,id);
            userService.update(updateWrapper);
        }
        return R.ok();
    }

    @PostMapping(value = "/changemail/{id}/{mail}/{code}")
    public R changeMail(@PathVariable("id") String id,@PathVariable("mail") String mail,@PathVariable("code") String code){
        //校验校验验证码
        //从redis获取发送的验证码
        String mailCode = (String) redisTemplate.opsForValue().get("fuyao:mail:code:" + mail);
        if(!code.equals(mailCode)) {
            return R.error().message("验证码错误");
        }

        //查询数据库中是否存在相同的邮箱
        Integer count = userService.count(new QueryWrapper<User>().eq("mail", mail));
        if(count.intValue() > 0) {
            return R.error().message("邮箱已存在");
        }

        LambdaUpdateWrapper<User> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(User::getMail,mail).eq(User::getId,id);
        userService.update(updateWrapper);
        return R.ok();
    }

}

